﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core;
using Cofe.Data;
using Cofe.Web.Interfaces;
using Newtonsoft.Json.Linq;

namespace Cofe.Web.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEWS)]
    public class EventLogResponseFormatter : IHttpResponseMessageFormatter
    {
        public bool CanCreateResponse(HttpRequestMessage request,
           object returnVal, ParameterDic pd, ResponseFormatterInfo info)
        {
            return (returnVal is CofeSystemEventLog) || (returnVal is IEnumerable<CofeSystemEventLog>);
        }


        private JObject writeCofeSystemLog(CofeSystemEventLog csel)
        {
            var retVal = new JObject();

            retVal.Add("id", csel.Id.Value);
            if (csel.EntryId.HasValue)
                retVal.Add("entryId", csel.EntryId.Value);
            retVal.Add("entryPath", csel.EntryParsePath);
            retVal.Add("time", csel.Time);
            retVal.Add("isFolder", csel.IsFolder);
            retVal.Add("type", ((ModifiedAction)csel.ChangeType).ToString());

            return retVal;
        }

        public JObject writeCofeSystemLog(IEnumerable<CofeSystemEventLog> csels)
        {
            var retVal = new JObject();
            retVal.Add("events", new JArray(from e in csels select writeCofeSystemLog(e)));
            return retVal;
        }

        public HttpResponseMessage CreateResponse(HttpRequestMessage request,
            object returnVal, ParameterDic pd, ResponseFormatterInfo info)
        {
            
            

            HttpResponseMessage result = new HttpResponseMessage(info.StatusCode);
            //result.Content = new StreamContent(bc.GetStream(info.ResourceAttribute.MediaType).Stream);
            //JObject
            //response = request.CreateResponse<JObject>(info.StatusCode,
            //        CofeServices.EntrySerializer.WriteEntry(returnVal as CofeSystemInfo, true));

            return result;
        }
        //CofeSystemEventLog
    }
}
